package io.zrpc.core.common.utils;

public class ClassLoaderUtils {
    /**
     * 得到当前 ClassLoader, 先从线程找, 找不到则从中间件所在 ClassLoader
     */
    public static ClassLoader getCurrentClassLoader(){
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null){
            cl = ClassLoaderUtils.getCurrentClassLoader();
        }
        return cl == null? ClassLoader.getSystemClassLoader() : cl;
    }

    /**
     * 根据某个类获取 ClassLoader,先从线程找, 找不到则从类加载的 ClassLoader 找, 最后由 SystemClassLoader 兜底
     */
    public static ClassLoader getClassLoader(Class<?> clazz){
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader != null){
            return loader;
        }
        if (clazz != null){
            loader = clazz.getClassLoader();
            if (loader != null){
                return loader;
            }
        }
        return ClassLoader.getSystemClassLoader();
    }
}
